<template>
  <basic-container>
    
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               >
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-view"
                   v-if="permission.database_delete"
                   @click="viewQuestion(scope.row)">预览
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-s-data"
                   v-if="permission.biz_question_send_record_batch_delete"
                   @click.stop="handleDelete">报表统计
        </el-button>
        <span style="padding-left:50px;">
          {{totInfo}}
        </span>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {exportBizQuestionSendListExcel,saveOrUpdateBizQuestionSendList,saveOrUpdateBizQuestionSendListList,saveBizQuestionSendList,saveBizQuestionSendListList,deleteBizQuestionSendList,queryBizQuestionSendList,queryBizQuestionSendListListPage,updateBizQuestionSendList,deleteBizQuestionSendListList} from '@/api/biz/question/bizQuestionSendListApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
export default {
  props: {
    batchNo:{
      type: String
    }
  },
  data() {
    return {
      totInfo:'',
      //文件选择器的打开方式 add新增、edit修改、view 查看
      openType: 'edit',
      // 当前打开form对话框操作类型 
      operateType: 'add',

      //如果做流程表单 请将次开关设置为true，否则设置为false
      isFlow: true,
      flowArea: {},
      
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      currentRow: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 125,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        editBtn: true,
        viewBtn: false,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        selection: false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        column: [
          
          {
            label: '填报人姓名',
            prop: 'fillInRealName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 50,
            overHidden: true,
            rules: [{
              message: '请输入填报人姓名',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          
          {
            label: '问卷类型',
            prop: 'questionnaireType', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            rules: [{
              message: '请输入问卷类型',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '填报状态',
            prop: 'status', 
            type: 'select', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            rules: [{
              message: '请输入问卷类型',
              required:  true,
              trigger: 'blur'
            }],
            dicData:[
              {label:'未开始',value:'0'},
              {label:'进行中',value:'1'},
              {label:'已完成',value:'2'},
              {label:'已失效',value:'3'}
            ],
          },
          {
            label: '进度(%)',
            prop: 'progressRate', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            rules: [{
              message: '请输入问卷类型',
              required:  true,
              trigger: 'blur'
            }],
            dicData:[
            ],
          },
          {
            label: '有效日期',
            prop: 'validDate', 
            type: 'date', 
            format:'yyyy-MM-dd hh:mm:ss',
            valueFormat: 'yyyy-MM-dd hh:mm:ss',
            value: this.$toolUtil.formatDate(new Date()),
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() + 3600 * 1000 * 24 <= Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 20,
            overHidden: true,
            rules: [{
              message: '请输入有效日期',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 20,
              message: '内容长度不能超过20字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','orgTree','genOrgTree','userInfo','permission','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.biz_question_send_list_add, false),
        viewBtn: this.vaildData(this.permission.biz_question_send_list_view, false),
        delBtn: this.vaildData(this.permission.biz_question_send_list_delete, false),
        editBtn: this.vaildData(this.permission.biz_question_send_list_edit, false),
        printBtn: this.vaildData(this.permission.biz_question_send_list_print, false),
        searchBtn:this.vaildData(this.permission.biz_question_send_list_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.singleBody.batchNo = this.batchNo;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 99999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryBizQuestionSendListListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        let beginCnt = 0;
        let notBeginCnt = 0;
        let finishCnt = 0;
        this.data.forEach(element => {
          if(element.status == '0'){
            notBeginCnt++;
          }
          else if(element.status == '1'){
            beginCnt++;
          }
          else if(element.status == '2'){
            finishCnt++;
          }
        });
        this.totInfo = '已下发：' + this.page.total + '人； 已完成：'+finishCnt+'人； 进行中： '+ beginCnt +'人';
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      let formatUser = {};
      // 解析用户名（用户ID）
      formatUser = this.$util.formatUserName(row.fillInUserName);
      this.reqParams.singleBody.fillInUserName = formatUser.userId; 
      this.reqParams.singleBody.fillInRealName = formatUser.userName;
      this.commonData = reqCommonMsg(this.reqParams)
      saveBizQuestionSendList(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) {
      this.reqParams.singleBody = row;
      let formatUser = {};
      // 解析用户名（用户ID）
      formatUser = this.$util.formatUserName(row.fillInUserName);
      this.reqParams.singleBody.fillInUserName = formatUser.userId; 
      this.reqParams.singleBody.fillInRealName = formatUser.userName;
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizQuestionSendList(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteBizQuestionSendList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.biz_question_send_list_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    /**
     * 批量导入
     */
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              projectNo:field[0].trim(),
              projectName:field[1].trim(),
              batchNo:field[2].trim(),
              fillInUserName:field[3].trim(),
              fillInRealName:field[4].trim(),
              questionnaireTemplateId:field[5].trim(),
              questionnaireType:field[6].trim(),
              questionnaireTitle:field[7].trim(),
              questionnaireNotice:field[8].trim(),
              mobileNo:field[9].trim(),
              generateFrequency:field[10].trim(),
              validDate:field[11].trim(),
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveBizQuestionSendListList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          this.$console.log(error);
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteBizQuestionSendListList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.operateType = 'edit';
        this.reqParams =  {
          singleBody: {
            id:this.form.id
          }
        }
        let commonData = reqCommonMsg(this.reqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryBizQuestionSendList(commonData).then(res => {
          this.form = res.data.body.singleBody;
          if(res.data.body.singleBody.fillInUserName){
          	this.form.fillInUserName = res.data.body.singleBody.fillInRealName+'('+ res.data.body.singleBody.fillInUserName +')';
          }
          loading.close();
          done();
        }, error => {
          this.$console.log(error);
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
        this.operateType = 'add';
        done();
      }
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },

    /**
     * 预览填报
     */
    viewQuestion(item){
      window.open('/#/website/questionSheet?qn='+Base64.encode(item.id),'_blank');
    },

    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportBizQuestionSendListExcel(this.commonData);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["bizType"]');
      this.findObject(this.option.column, 'bizType').dicData = dicData.bizType;
    },
    
    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      })
    },
  },
  created() {
    this.onLoad(this.page);  
    this.showColumn = this.$getStore({name: this.userInfo.userId+'bizQuestionSendListColumn'});
    //获取业务字典
    // setTimeout(() => {
    //  this.getBizDict();
    // }, 1000);
    
    //加载机构
    let getOrgTreeTimer = setInterval(() => {
      if(this.genOrgTree){
        let orgTree = [];
        this.genOrgTree.forEach(element => {
          if(element.orgType == '1'){
            orgTree.push(element);
          }
        });
        clearInterval(getOrgTreeTimer);
      }
    }, 100);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'bizQuestionSendListColumn', content: this.showColumn});
      },
      deep: true
    }
  }
  // watch: {
  //   batchNo: {
  //     handler (val) {
  //       this.$console.log('batchNo===',this.batchNo);
  //       this.singleBody={batchNo: this.batchNo};
  //       this.onLoad(this.page);
  //     },
  //     deep: true
  //   }
  // }
};
</script>
